package org.wei.utils;

import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

public class Pool<K, V> {
	private List<Entry<K, V>> list = new ArrayList<Entry<K, V>>();
	private int maxSize = 100;

	public Pool() {
	}

	public Pool(int maxSize) {
		this.maxSize = maxSize;
	}

	public void add(K key, V value) {
		Entry<K, V> entry = new SimpleEntry<K, V>(key, value);
		int index = getIndex(entry);
		if (index >= 0) {
			list.set(index, entry);
		} else {
			if (list.size() >= maxSize) {
				list.remove(0);
			}
			list.add(entry);
		}
	}

	private int getIndex(Entry<K, V> entry) {
		for (int i = 0; i < list.size(); i++) {
			Entry<K, V> e = list.get(i);
			if (e.getKey() == null) {
				if (entry.getKey() == null) {
					return i;
				}
				return -1;
			}
			if (e.getKey().equals(entry.getKey())) {
				return i;
			}
		}
		return -1;
	}

	public V get(K key) {
		for (int i = 0; i < list.size(); i++) {
			Entry<K, V> entry = list.get(i);
			if (entry.getKey() == null) {
				if (key == null) {
					list.remove(i);
					list.add(entry);
					return entry.getValue();
				}
			} else if (entry.getKey().equals(key)) {
				list.remove(i);
				list.add(entry);
				return entry.getValue();
			}
		}

		return null;
	}

	public int size() {
		return list.size();
	}

}
